package design.patterns.behavioral;

import java.util.ArrayList;
import java.util.List;

/**
 * 备忘录模式
 * 解释：
 * 备忘录模式是一种行为设计模式，
 * 允许在不暴露对象实现细节的情况下保存和恢复对象之前的状态。
 */


public class E_Memento {
    public static void main(String[] args) {
        TextInput textInput = new TextInput();
        History history = new History();

        textInput.insertText("Hello");
        history.push(textInput.getBackUp());
        System.out.println(textInput);

        textInput.insertText("!");
        history.push(textInput.getBackUp());
        System.out.println(textInput);

        textInput.insertText("World");
        history.push(textInput.getBackUp());
        System.out.println(textInput);

        textInput.insertText("!");
        history.push(textInput.getBackUp());
        System.out.println(textInput);

        System.out.println(history.backUpList);

        textInput.setStr(history.undo(1));
        System.out.println(textInput);

        textInput.setStr(history.undo(2));
        System.out.println(textInput);

        textInput.insertText("Hello");
        history.push(textInput.getBackUp());
        System.out.println(textInput);

        textInput.setStr(history.undo(1));
        System.out.println(textInput);



    }

}


class TextInput{
    private final BackUp backUp = new BackUp();
    private String str= "";

    public void insertText(String strText){
        str +=strText;
        backUp.setStr(str);
    }


    public void setStr(String str) {
        this.str = str;
    }

    public BackUp getBackUp() {
        return backUp;
    }

    public String getStr() {
        return str;
    }

    @Override
    public String toString() {
        return "TextInput{" +
                "str='" + str + '\'' +
                '}';
    }
}

class History{
    List<BackUp> backUpList=new ArrayList<>();
    void push(BackUp backUp){
        backUpList.add(new BackUp(backUp.getStr()));
    }
    String undo(Integer times){
        Integer backListLen = backUpList.size();
        if (backListLen>0&&times<=backListLen){
            int currentIndex =backListLen - times-1;
            BackUp backup = backUpList.get(currentIndex);
           backUpList = backUpList.subList(0, currentIndex);
            return backup.getStr();
        }
        return "";
    }

}
class BackUp{
    private String str;

    public void setStr(String str) {
        this.str = str;
    }
    public BackUp(){}
    public BackUp(String str) {
        this.str = str;
    }

    public String getStr() {
        return str;
    }

    @Override
    public String toString() {
        return "BackUp{" +
                "str='" + str + '\'' +
                '}';
    }
}